package SystemDefault

import (
	"../../Config" //配置
	"../../Const"  //常量
	"../../Run"
	"errors"
	"fmt"     //基本
	"reflect" //反射
	"strings"
)

//定义接口
type Site interface {
	Main()
	Index()
	Test()
	Route()
}

//
type SystemSite struct {
}

func (systemSite SystemSite) Main(params Run.Params) {
	if !Const.DEBUG {
		fmt.Println("调试模式 ：未开启")
		(new(SystemSite)).Index(params)
	} else {
		fmt.Println("调试模式 ：已开启")
		(new(SystemSite)).Test(params)
	}
}

func (systemSite SystemSite) Index(params Run.Params) {
	fmt.Println("主调方法：Index")
	fmt.Println(params)
	exist, err := (new(SystemSite)).Route(params)
	if exist {
		fmt.Println(err)
	}
}

func (systemSite SystemSite) Test(params Run.Params) {
	fmt.Println("主调方法 ：Test")
	fmt.Println("主调参数 ：")
	fmt.Println(params)
	(new(SystemSite)).Route(params)
}

func (systemSite SystemSite) Route(params Run.Params) (bool, error) {
	var router Config.RouterInterface
	router = new(Config.Router)
	routes := router.Table()
	fmt.Println("路由表信息 ：")
	fmt.Println(routes)
	var routeExist bool = false
	for routeKey, routeValue := range routes {
		if routeKey == params.Url {
			fmt.Println("找到匹配的路由数据，信息如下：")
			fmt.Println(routeValue)
			for routeItemKey, controller := range routeValue {
				routeItemInfo := strings.Split(routeItemKey, "/")
				function := (routeItemInfo[len(routeItemInfo)-1])
				fmt.Println("控制器：")
				fmt.Println(controller)
				fmt.Println("控制器方法：")
				fmt.Println(function)
				InvokeObjectMethod(controller, function, params)
				routeExist = true
				return true, nil
			}
		}
	}
	if !routeExist {
		return false, errors.New("未找到匹配路由")
	}
	return true, nil
}

func InvokeObjectMethod(objectType reflect.Type, methodName string, args ...interface{}) {
	inputs := make([]reflect.Value, len(args))
	for i, _ := range args {
		inputs[i] = reflect.ValueOf(args[i])
	}
	reflect.New(objectType).MethodByName(methodName).Call(inputs)
}

//InvokeObjectMethod(new(YourT2), "MethodFoo", 10, "abc")
//reflect.ValueOf(object).MethodByName(methodName).Call(inputs)
